/*
 * @Author: zhangyang
 * @Date: 2024-05-29 14:06:34
 * @LastEditTime: 2024-06-05 16:25:16
 * @Description: 
 * @LastEditors: Please set LastEditors
 * ██████╗ ██╗     ██╗   ██╗███████╗███████╗██╗   ██╗ ██████╗ ██╗   ██╗███╗   ██╗ ██████╗               ██╗    ██╗███████╗██████╗ 
 * ██╔══██╗██║     ██║   ██║██╔════╝██╔════╝╚██╗ ██╔╝██╔═══██╗██║   ██║████╗  ██║██╔════╝               ██║    ██║██╔════╝██╔══██╗
 * ██████╔╝██║     ██║   ██║█████╗  ███████╗ ╚████╔╝ ██║   ██║██║   ██║██╔██╗ ██║██║  ███╗    █████╗    ██║ █╗ ██║█████╗  ██████╔╝
 * ██╔══██╗██║     ██║   ██║██╔══╝  ╚════██║  ╚██╔╝  ██║   ██║██║   ██║██║╚██╗██║██║   ██║    ╚════╝    ██║███╗██║██╔══╝  ██╔══██╗
 * ██████╔╝███████╗╚██████╔╝███████╗███████║   ██║   ╚██████╔╝╚██████╔╝██║ ╚████║╚██████╔╝              ╚███╔███╔╝███████╗██████╔╝
 * ╚═════╝ ╚══════╝ ╚═════╝ ╚══════╝╚══════╝   ╚═╝    ╚═════╝  ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝                ╚══╝╚══╝ ╚══════╝╚═════╝
 * Copyright (c) 2024 to current by BluesYoung-web, All Rights Reserved. 
 */
import '/util/log_utils.dart';
import '/database/init.dart';

enum CategrayType {
  outcome,
  income,
}

extension CategrayTypeExtension on CategrayType {
  String get value => ['outcome', 'income'][index];
  String get label => ['支出', '收入'][index];
}

class ICategray {
  final int? autoid;
  final String? icon;
  final String name;
  final CategrayType type;

  const ICategray({
    this.autoid,
    this.icon,
    required this.name,
    required this.type,
  });
}

class DataBaseCategray {
  /// 默认分类列表
  static const List<ICategray> defaultCategrayList = [
    /// 默认收入
    ICategray(autoid: 1, name: '工资', icon: '💰', type: CategrayType.income),
    ICategray(autoid: 2, name: '奖金', icon: '🥇', type: CategrayType.income),
    ICategray(autoid: 3, name: '投资收益', icon: '💲', type: CategrayType.income),
    ICategray(autoid: 4, name: '兼职收入', icon: '👷', type: CategrayType.income),
    ICategray(autoid: 5, name: '其他收入', icon: '💡', type: CategrayType.income),

    /// 默认支出
    ICategray(autoid: 6, name: '餐饮', icon: '🍚', type: CategrayType.outcome),
    ICategray(autoid: 7, name: '买菜', icon: '🥬', type: CategrayType.outcome),
    ICategray(autoid: 8, name: '买水果', icon: '🍇', type: CategrayType.outcome),
    ICategray(autoid: 9, name: '购物', icon: '🛍️', type: CategrayType.outcome),
    ICategray(autoid: 10, name: '交通', icon: '🚗', type: CategrayType.outcome),
    ICategray(autoid: 11, name: '房租', icon: '🏠', type: CategrayType.outcome),
    ICategray(autoid: 12, name: '水电燃', icon: '💧', type: CategrayType.outcome),
    ICategray(autoid: 13, name: '通讯', icon: '📱', type: CategrayType.outcome),
    ICategray(autoid: 14, name: '娱乐', icon: '🎮', type: CategrayType.outcome),
    ICategray(autoid: 15, name: '医疗', icon: '🏥', type: CategrayType.outcome),
    ICategray(autoid: 16, name: '学习', icon: '📚', type: CategrayType.outcome),
    ICategray(autoid: 17, name: '社交', icon: '👫', type: CategrayType.outcome),
    ICategray(autoid: 18, name: '礼物', icon: '🎁', type: CategrayType.outcome),
    ICategray(autoid: 19, name: '旅行', icon: '✈️', type: CategrayType.outcome),
    ICategray(autoid: 20, name: '其他支出', icon: '🤷', type: CategrayType.outcome),
  ];

  /// 获取所有分类
  static Future<List<ICategray>> getAllCategray(CategrayType type) async {
    var db = await DataBase.openDB();

    final List<Map<String, Object?>> resultSet = await db.query(
        DataBase.tableCategray,
        columns: ['autoid', 'name', 'icon', 'type'],
        where: 'type = ?',
        whereArgs: [type.value]);

    // print('resultSet: ${resultSet.toString()}');

    List<ICategray> list = [];

    for (final Map<String, dynamic> row in resultSet) {
      // print(row.toString());

      list.add(ICategray(
        autoid: row['autoid'],
        name: row['name'],
        type: row['type'] == 'income'
            ? CategrayType.income
            : CategrayType.outcome,
        icon: row['icon'],
      ));
    }

    if (list.isEmpty) {
      // print('list is empty, inject default');

      final batch = db.batch();

      list = defaultCategrayList.where((item) => item.type == type).toList();

      /// 将默认分类插入
      for (final ICategray item in list) {
        batch.insert(DataBase.tableCategray, {
          'name': item.name,
          'icon': item.icon,
          'type': item.type.value,
        });
      }

      try {
        await batch.commit(noResult: true);
      } catch (e) {
        Log.e(e.toString());
        db.close();
      }
    }

    return list;
  }

  /// 新增分类
  static Future<void> addCategray(ICategray item) async {
    var db = await DataBase.openDB();

    try {
      await db.insert(DataBase.tableCategray, {
        'name': item.name,
        'icon': item.icon,
        'type': item.type.value,
      });
    } catch (e) {
      Log.e(e.toString());
      db.close();
    }
  }

  /// 删除分类
  static Future<void> deleteCategray(int autoid) async {
    var db = await DataBase.openDB();

    try {
      await db.delete(DataBase.tableCategray,
          where: 'autoid = ?', whereArgs: [autoid]);
    } catch (e) {
      Log.e(e.toString());
      db.close();
    }
  }
}
